package com.yimils.core.hardware.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yimils.core.common.config.BaseConfig;
import com.yimils.core.common.dto.GetQueryParams;
import com.yimils.core.common.oss.OssUtils;
import com.yimils.core.common.qrcode.QRCodeUtils;
import com.yimils.core.hardware.beanUtils.RetailVoBeanUtils;
import com.yimils.core.hardware.dto.ReqAddHwRetail;
import com.yimils.core.hardware.entity.GridEntity;
import com.yimils.core.hardware.entity.RetailEntity;
import com.yimils.core.hardware.mapper.RetailMapper;
import com.yimils.core.hardware.vo.RetailVo;
import com.yimils.core.sys.entity.UserEntity;
import com.yimils.core.sys.entity.UserRoleEntity;
import com.yimils.core.sys.service.UserRoleService;
import com.yimils.core.sys.utils.PageUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service("retailService")
public class RetailServiceImpl extends ServiceImpl<RetailMapper, RetailEntity> implements RetailService {
    @Autowired
    private OssUtils ossUtils;
    @Autowired
    private QRCodeUtils qrCodeUtils;

    @Autowired
    private BaseConfig baseConfig;

    private String qrDir = "hw_retail_qr";

    @Resource(name = "gridService")
    private GridService gridService;

    @Autowired
    private PageUtils pageUtils;

    @Autowired
    private RetailVoBeanUtils retailVoBeanUtils;

    @Transactional
    @Override
    public boolean createHWRetail(ReqAddHwRetail dto) {
        RetailEntity entity = new RetailEntity();
        entity.setSn(dto.getSn());
        entity.setName(dto.getName());
        entity.setBtAddr(dto.getBtAddr());
        entity.setBattery(100);
        entity.setOnline(0);
        entity.setCreateTime(LocalDateTime.now());
        entity.setPartnerId(dto.getPartnerId());
        entity.setHotelId(dto.getHotelId());
        entity.setFeederId(dto.getFeederId());
        entity.setRoom(dto.getRoom());
        entity.setType(dto.getType());
        String qrUrl = createAndUploadQR(dto.getSn(), dto.getBtAddr());
        entity.setQrCodeUrl(qrUrl);
        if (save(entity)) {
            List<GridEntity> grids = new ArrayList<>();
            for (int i = 1; i <= 9; i++) {
                GridEntity gridEntity = new GridEntity();
                gridEntity.setHardwareId(entity.getId());
                gridEntity.setCode(i);
                gridEntity.setState(0);
                grids.add(gridEntity);
            }
            return gridService.saveBatch(grids);
        }
        return false;
    }

    @Override
    public IPage<RetailVo> getListForPage(GetQueryParams queryParams) {
        Page<RetailEntity> pageParams = new Page<>(queryParams.getPageNo() == null ? 1 : queryParams.getPageNo(),
                queryParams.getPageSize() == null ? 10 : queryParams.getPageSize());

        pageUtils.makePageParams(queryParams, pageParams);
        LambdaQueryWrapper<RetailEntity> qw = new LambdaQueryWrapper<>();
        if (queryParams.getPartnerId() != null) {
            qw.eq(RetailEntity::getPartnerId, queryParams.getPartnerId());
        }
        if (queryParams.getHotelId() != null) {
            qw.eq(RetailEntity::getHotelId, queryParams.getHotelId());
        }
        if (queryParams.getFeederId() != null) {
            qw.eq(RetailEntity::getFeederId, queryParams.getFeederId());
        }

        IPage<RetailEntity> entities = page(pageParams, qw);

        return retailVoBeanUtils.deepClone(entities);
    }

    @Override
    public RetailVo getRetailVoById(Long id) {
        RetailEntity entity = getById(id);
        return retailVoBeanUtils.makeVoNode(entity);
    }

    @Override
    public boolean modify(RetailEntity entity) {
        RetailEntity old = getById(entity.getId());
        if (!old.getSn().equalsIgnoreCase(entity.getSn()) ||
                !old.getBtAddr().equalsIgnoreCase(entity.getBtAddr())) {
            entity.setQrCodeUrl(createAndUploadQR(entity.getSn(), entity.getBtAddr()));
        }
        return saveOrUpdate(entity);
    }

    private String createAndUploadQR(String sn, String btAddr) {
        StringBuilder sb = new StringBuilder();
        sb.append(baseConfig.getScheme()).append(baseConfig.getHost())
                .append("?macno=").append(sn)
                .append("&mac_id=").append(btAddr);
        String content = sb.toString();
        qrCodeUtils.createQRCode(content, sn, baseConfig.getLocalPath(), baseConfig.getLocalFileName());
        String objectName = qrDir + "/" + sn + ".jpg";
        ossUtils.uploadQR(objectName, baseConfig.getLocalPath() + baseConfig.getLocalFileName());
        sb = new StringBuilder();

        sb.append("https://").
                append(ossUtils.getBucketName()).append(".").
                append(ossUtils.getEndpoint()).append("/").
                append(objectName);

        return sb.toString();
    }
}
